//   Copyright 2012,2013 Vaughn Vernon
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.
package com.saasovation.common.port.adapter.persistence.hibernate;

import com.saasovation.common.notification.Notification;
import com.saasovation.common.notification.PublishedNotificationTracker;
import com.saasovation.common.notification.PublishedNotificationTrackerStore;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;

import java.util.List;

public class HibernatePublishedNotificationTrackerStore
        implements PublishedNotificationTrackerStore {

    private final SessionFactory sessionFactory;

    private String typeName;

    public HibernatePublishedNotificationTrackerStore(SessionFactory sessionFactory) {
        super();
        this.sessionFactory = sessionFactory;
        this.typeName = "default";
    }

    public HibernatePublishedNotificationTrackerStore(SessionFactory sessionFactory,
                                                      String aPublishedNotificationTrackerType) {
        super();
        this.sessionFactory = sessionFactory;
        this.setTypeName(aPublishedNotificationTrackerType);
    }

    @Override
    public PublishedNotificationTracker publishedNotificationTracker() {
        return this.publishedNotificationTracker(this.typeName());
    }

    @Override
    public PublishedNotificationTracker publishedNotificationTracker(String aTypeName) {
        Query<PublishedNotificationTracker> query = this.sessionFactory.getCurrentSession()
                .createQuery("from com.saasovation.common.notification.PublishedNotificationTracker as pnt "
                                + "where pnt.typeName = :typeName",
                        PublishedNotificationTracker.class);
        query.setParameter("typeName", aTypeName);
        PublishedNotificationTracker tracker = null;
        try {
            tracker = query.uniqueResult();
        } catch (Exception e) {
            // fall through
        }
        if (tracker == null) {
            tracker = new PublishedNotificationTracker(this.typeName());
        }
        return tracker;
    }

    @Override
    public void trackMostRecentPublishedNotification(PublishedNotificationTracker tracker,
                                                     List<Notification> aNotifications) {
        int lastIndex = aNotifications.size() - 1;
        if (lastIndex >= 0) {
            long mostRecentId = aNotifications.get(lastIndex).notificationId();
            tracker.setMostRecentPublishedNotificationId(mostRecentId);
            this.sessionFactory.getCurrentSession().merge(tracker);
        }
    }

    @Override
    public String typeName() {
        return typeName;
    }

    private void setTypeName(String aTypeName) {
        this.typeName = aTypeName;
    }
}
